package com.gill.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @Description: zookeeper 节点自定义访问权限的demo演示
 */
public class ZKNodeAclCustomize implements Watcher {

	private ZooKeeper zookeeper = null;

	public static final String zkServerPath = "env:2181";
	public static final Integer timeout = 5000;

	public ZKNodeAclCustomize() {}

	public ZKNodeAclCustomize(String connectString) {
		try {
			zookeeper = new ZooKeeper(connectString, timeout, new ZKNodeAclCustomize());
		} catch (IOException e) {
			e.printStackTrace();
			if (zookeeper != null) {
				try {
					zookeeper.close();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	public void createZKNode(String path, byte[] data, List<ACL> acls) {
		
		String result = "";
		try {
			result = zookeeper.create(path, data, acls, CreateMode.PERSISTENT);
			System.out.println("创建节点：\t" + result + "\t成功...");
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
	}
	
	public static void main(String[] args) throws Exception {
	
		ZKNodeAclCustomize zkServer = new ZKNodeAclCustomize(zkServerPath);

		// 自定义用户认证访问
		List<ACL> acls = new ArrayList<ACL>();//权限列表，以下是采用digest认证机制，定义两个用户，同时对"用户名:密码"进行加密
		Id imooc1 = new Id("digest", DigestAuthenticationProvider.generateDigest("imooc1:123456"));
		Id imooc2 = new Id("digest", DigestAuthenticationProvider.generateDigest("imooc2:123456"));
		acls.add(new ACL(ZooDefs.Perms.ALL, imooc1));//为用户设置权限
		acls.add(new ACL(ZooDefs.Perms.READ, imooc2));
		acls.add(new ACL(ZooDefs.Perms.DELETE | ZooDefs.Perms.CREATE, imooc2));
		zkServer.createZKNode("/aclimooc/testdigest", "testdigest".getBytes(), acls);//前提是要有/aclimooc

		// 以下是一些测试：注册过的用户必须通过addAuthInfo才能操作节点，参考命令行 addauth
//		zkServer.getZookeeper().addAuthInfo("digest", "imooc1:123456".getBytes());
//		zkServer.createZKNode("/aclimooc/testdigest/childtest", "childtest".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL);
//		Stat stat = new Stat();
//		byte[] data = zkServer.getZookeeper().getData("/aclimooc/testdigest", false, stat);
//		System.out.println(new String(data));
//		zkServer.getZookeeper().setData("/aclimooc/testdigest", "now".getBytes(), 1);

	}

	public ZooKeeper getZookeeper() {
		return zookeeper;
	}
	public void setZookeeper(ZooKeeper zookeeper) {
		this.zookeeper = zookeeper;
	}

	@Override
	public void process(WatchedEvent event) {
		
	}
}

